﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using Rookey.Frame.IMCore;

namespace Rookey.Frame.IMWeb
{
	public partial class Lesktop_CustomService : System.Web.UI.Page
	{
		static Regex IPReg = new Regex(@"[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}");
		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
                String sessionId = Guid.NewGuid().ToString().ToUpper();

                String visitorNickname = String.IsNullOrEmpty(Request.QueryString["Nickname"]) ? "访客" : Request.QueryString["Nickname"];
                String visitorName = String.IsNullOrEmpty(Request.QueryString["Name"]) ? Guid.NewGuid().ToString().ToUpper().Replace("-", "") : Request.QueryString["Name"];
                AccountInfo cu = ServerImpl.Instance.GetCurrentUser(Context);
                if (String.IsNullOrEmpty(Request.QueryString["Name"]))
                {
                    cu = ServerImpl.Instance.GetCurrentUser(Context);
                }
                else
                {
                    cu = AccountImpl.Instance.GetUserInfo(visitorName);
                }
                if (cu == null)
                {
                    AccountImpl.Instance.CreateTempUser(visitorName, visitorNickname);
                    cu = AccountImpl.Instance.GetUserInfo(visitorName);
                }
				if (cu.Nickname != visitorNickname)
				{
					Hashtable updateValues = new Hashtable();
					updateValues["Nickname"] = visitorNickname;
					AccountImpl.Instance.UpdateUserInfo(cu.Name, updateValues);
				}

                Rookey.Frame.IMCore.ServerImpl.Instance.Login(sessionId, Context, cu.Name, DateTime.Now.AddYears(1));

				Response.AddHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

				HtmlInputHidden data_json = FindControl("data_json") as HtmlInputHidden;
				data_json.Value = Utility.RenderHashJson(
					"User", cu.DetailsJson,
					"Peer", AccountImpl.Instance.GetUserInfo(Request.QueryString["Peer"]).DetailsJson,
					"SessionID", sessionId
				);
			}
			catch (Exception ex)
			{
				ServerImpl.Instance.WriteLog(String.Format("{0}:\r\n{1}", ex.GetType().Name, ex.StackTrace));
				throw;
			}
		}
	}
}